<?php

namespace app\api\controller\mall;

use app\common\controller\Api;
use addons\litestore\model\Litestoreorder;

use addons\third\model\Third;
use app\common\model\meet\Config;
use app\common\model\meet\Coupon;
use app\common\model\meet\CouponTemplate;
use app\common\model\meet\Cron;
use EasyWeChat\Factory as WXPAY_APP;

class Order extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['callback_for_wxapp', 'callback_for_wxgzh'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->model = new Litestoreorder;

    }

    public function buyNow()
    {
        $goods_id = $this->request->request('goods_id');
        $goods_num = $this->request->request('goods_num');
        $goods_sku_id = $this->request->request('goods_sku_id');
        $delivery_method = $this->request->request('delivery_method', 0);
        $coupon_id = $this->request->request('coupon_id', 0);

        $order = $this->model->getBuyNow($this->user_id, $goods_id, $goods_num, $goods_sku_id, $delivery_method, $coupon_id);

        return $this->success('获取成功', $order);
    }

    public function buyNow_pay()
    {
        $goods_id = $this->request->request('goods_id');
        $goods_num = $this->request->request('goods_num');
        $goods_sku_id = $this->request->request('goods_sku_id');
        $delivery_method = $this->request->request('delivery_method', 0);
        $coupon_id = $this->request->request('coupon_id', 0);

        $order = $this->model->getBuyNow($this->user_id, $goods_id, $goods_num, $goods_sku_id, $delivery_method, $coupon_id);

        if ($this->model->hasError()) {
            return $this->error($this->model->getError());
        }

        // 创建订单
        if ($this->model->order_add($this->user_id, $order, $delivery_method)) {
            // 发起微信支付
            if ($this->request->request('type') && $this->request->request('type') == 'gzh') {
                $this->init_wx_pay_for_gzh(true);
                $this->make_wx_pay('wechat');
            } else {
                $this->init_wx_pay_for_wxapp();
                $this->make_wx_pay('wxapp');
            }
        }
        $error = $this->model->getError() ?: '订单创建失败';
        return $this->error($error);

    }

    public function getCouponList()
    {
        $limit = $this->request->get('limit', '');
        $goods_ids = $this->request->get('goods_ids', '');

        $model = new Coupon();

        $condition = [
            'status' => $model::STATUS_NOT_USE,
            'user_id' => $this->auth->id,
            'end_time' => ['gt', time()],
            'limit' => ['elt', $limit]
        ];

        $orCondition = [
            'status' => $model::STATUS_NOT_USE,
            'user_id' => $this->auth->id,
            'end_time' => 0,//无期限
            'limit' => ['elt', $limit]
        ];

//        if (!empty($limit)) {
//            $condition['limit'] = ['elt', $limit];
//            $condition['start_time'] = ['elt', time()];
//            $orCondition['limit'] = ['elt', $limit];
//        }

        $list = $model
            ->where(function ($query) use ($condition) {
                $query->where($condition);
            })
            ->whereOr(function ($query) use ($orCondition) {
                $query->where($orCondition);
            })
            ->order('createtime', 'desc')
            ->select();

        $new_list = [];
        if ($list) {
            $goods_ids_arr = $goods_ids ? explode(',', $goods_ids) : [];

            foreach ($list as $key => $value) {
                if ($value['available_type'] === CouponTemplate::AVAILABLE_TYPE_RESERVATION) {
                    continue;
                }

                if ($value['range_type'] === CouponTemplate::RANGE_TYPE_APPOINT) {
                    $range_goods_arr = explode(',', $value['range_goods']);
                    $intersect = array_intersect($range_goods_arr, $goods_ids_arr);

                    if (empty($intersect)) {
                        continue;
                    }
                }

                $validity = '';

                $range = '';

                if ($value['status'] == $model::STATUS_NOT_USE) {
                    if (!empty($value['start_time'])) {
                        $validity = date('Y-m-d', $value['end_time']) . ' 前有效';
                    } else {
                        $validity = '未使用前永久有效';
                    }
                }

                if ($value['available_type'] === CouponTemplate::AVAILABLE_TYPE_MALL) {
                    $range = '仅限购买商品使用';
                } else if ($value['available_type'] === CouponTemplate::AVAILABLE_TYPE_RESERVATION) {
                    $range = '仅限预约使用';
                } else if ($value['available_type'] === CouponTemplate::AVAILABLE_TYPE_ALL) {
                    $range = '全场通用';
                }

                $value['range'] = $range;

                $value['validity'] = $validity;

                $new_list[] = $value;
            }
        }

        $this->success('', ['list' => $new_list]);
    }

    public function Get_order_num()
    {
        $NoPayNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '10', 'freight_status' => '10', 'order_status' => '10', 'receipt_status' => '10'])->count();
        $NoFreightNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '20', 'freight_status' => '10', 'order_status' => '10', 'receipt_status' => '10'])->count();
        $NoReceiptNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '20', 'freight_status' => '20', 'order_status' => '10', 'receipt_status' => '10'])->count();
        return $this->success('', ['NoPayNum' => $NoPayNum, 'NoFreightNum' => $NoFreightNum, 'NoReceiptNum' => $NoReceiptNum]);
    }

    public function my()
    {
        $list = $this->model->getList($this->user_id);
        return $this->success('', $list);
    }

    public function getOrderList()
    {
        $page = $this->request->get('page/d', 1);
        $page_size = $this->request->get('page_size/d', 10);
        $status = $this->request->get('status/d', 0);

        $condition = [
            'user_id' => $this->auth->id
        ];

        if (!empty($status)) {
            switch ($status) {
                case 10:    //未付款
                    $condition['pay_status'] = 10;
                    $condition['freight_status'] = 10;
                    $condition['order_status'] = 10;
                    $condition['receipt_status'] = 10;
                    break;
                case 20:    //待发货
                    $condition['pay_status'] = 20;
                    $condition['freight_status'] = 10;
                    $condition['order_status'] = 10;
                    $condition['receipt_status'] = 10;
                    $condition['delivery_method'] = 0;
                    break;
                case 30:    //待收货
                    $condition['pay_status'] = 20;
                    $condition['freight_status'] = 20;
                    $condition['order_status'] = 10;
                    $condition['receipt_status'] = 10;
                    $condition['delivery_method'] = 0;
                    break;
                case 40:    //已完成
                    $condition['pay_status'] = 20;
                    $condition['freight_status'] = 20;
                    $condition['order_status'] = 30;
                    $condition['receipt_status'] = 20;
                    break;
                case 50:    //待核销
                    $condition['pay_status'] = 20;
                    $condition['order_status'] = 10;
                    $condition['delivery_method'] = 1;
                    break;
            }

        }

        $list = $this->model->with(['goods'])->order(['createtime' => 'desc'])->where($condition)->paginate(['list_rows' => $page_size, 'page' => $page]);

        foreach ($list as $key => $order) {
            $goodsList = [];
            foreach ($order['goods'] as $index => $item) {
                $item['image'] = cdnurl(explode(",", $item['images'])[0], true);
                $item['sku_image'] = $item['spec']['spec_image'] == '' ? $item['image'] : cdnurl($item['spec']['spec_image'], true);
                $goodsList[] = $item;
            }
            $order['goods'] = $goodsList;

            if ($order['pay_status'] == 10 && $order['freight_status'] == 10 && $order['order_status'] == 10 && $order['receipt_status'] == 10) {
                $order['status_text'] = '待支付';
            }

            if ($order['pay_status'] == 20 && $order['freight_status'] == 10 && $order['order_status'] == 10 && $order['receipt_status'] == 10) {
                if ($order['delivery_method'] == 1) {
                    $order['status_text'] = '待核销';
                } else {
                    $order['status_text'] = '待发货';
                }
            }

            if ($order['pay_status'] == 20 && $order['freight_status'] == 20 && $order['order_status'] == 10 && $order['receipt_status'] == 10) {
                $order['status_text'] = '待收货';
            }

            if ($order['pay_status'] == 20 && $order['freight_status'] == 20 && $order['order_status'] == 30 && $order['receipt_status'] == 20) {
                if ($order['delivery_method'] == 1) {
                    $order['status_text'] = '已核销';
                } else {
                    $order['status_text'] = '已完成';
                }
            }

            if ($order['order_status'] == 20) {
                $order['status_text'] = '已取消';
            }
        }

        $this->success('', $list);
    }

    public function detail()
    {
        $id = $this->request->request('id');
        $order = $this->model->getOrderDetail($id, $this->user_id);

        if ($order['pay_status'] == 10 && $order['freight_status'] == 10 && $order['order_status'] == 10 && $order['receipt_status'] == 10) {
            $order['status_text'] = '待支付';
        }

        if ($order['pay_status'] == 20 && $order['freight_status'] == 10 && $order['order_status'] == 10 && $order['receipt_status'] == 10) {
            if ($order['delivery_method'] == 1) {
                $order['status_text'] = '待核销';
            } else {
                $order['status_text'] = '待发货';
            }
        }

        if ($order['pay_status'] == 20 && $order['freight_status'] == 20 && $order['order_status'] == 10 && $order['receipt_status'] == 10) {
            $order['status_text'] = '待收货';
        }

        if ($order['pay_status'] == 20 && $order['freight_status'] == 20 && $order['order_status'] == 30 && $order['receipt_status'] == 20) {
            if ($order['delivery_method'] == 1) {
                $order['status_text'] = '已核销';
            } else {
                $order['status_text'] = '已完成';
            }
        }

        if ($order['order_status'] == 20) {
            $order['status_text'] = '已取消';
        }

        if ($order['goods']) {
            $refund_model = new \app\common\model\mall\Refund();
            foreach ($order['goods'] as $key => $value) {
                $refund_id = 0;
                if ($value['refund_status'] > 0) {
                    $refund_id = $refund_model->where(['order_goods_id' => $value['id'], 'refund_status' => ['in', [0, 3, 4, 5]]])->value('id');
                }

                $value['refund_id'] = $refund_id;
            }
        }

        return $this->success('', ['order' => $order]);
    }

    public function cart_pay()
    {
        $ids = $this->request->post('ids', '');
        $delivery_method = $this->request->request('delivery_method', 0);
        $coupon_id = $this->request->request('coupon_id', 0);
        $order = $this->model->getCart($this->user_id, $ids, $delivery_method, $coupon_id);

        // 创建订单
        if ($this->model->order_add($this->user_id, $order, $delivery_method)) {
            if (!empty($ids)) {
                $ids_arr = explode(',', $ids);
                foreach ($ids_arr as $k => $v) {
                    $this->model->deleteByIndex($this->user_id, $v);
                }
            } else {
                // 清空购物车
                $this->model->CarclearAll($this->user_id);
            }


            // 发起微信支付
            if ($this->request->request('type') && $this->request->request('type') == 'gzh') {
                $this->init_wx_pay_for_gzh(true);
                $this->make_wx_pay('wechat');
            } else {
                $this->init_wx_pay_for_wxapp();
                $this->make_wx_pay('wxapp');
            }
        }
        $this->error($this->model->getError() ?: '订单创建失败');
    }

    public function finish()
    {
        $id = $this->request->post("id");
        $order = $this->model;
        if ($order->finish($this->user_id, $id)) {
            //删除订单自动收货的定时任务
            (new Cron())->where(['event' => 'CronMallOrderComplete', 'relate_id' => $id])->delete();
            return $this->success(__('Operation completed'));
        }
        return $this->error($order->getError());
    }

    public function cancel()
    {
        $id = $this->request->post("id");
        $order = $this->model->getOrderDetail($id, $this->user_id);

        if ($order->cancel($this->user_id, $id)) {
            //删除订单自动取消的定时任务
            (new Cron())->where(['event' => 'CronMallOrderCancel', 'relate_id' => $id])->delete();
            return $this->success(__('Operation completed'));
        }

        return $this->error($order->getError());
    }

    public function order_pay()
    {
        $id = $this->request->post("id");
        $order = $this->model->getOrderDetail($id, $this->user_id);
        if (!$order) {
            $this->error($this->model->getError());
        }
        if (!$order->checkGoodsStatusFromOrder($order['goods'])) {
            return $this->error($order->getError());
        }
        $this->model = $order;
        // 发起微信支付
        if ($this->request->post('type') && $this->request->post('type') == 'gzh') {
            $this->init_wx_pay_for_gzh(true);
            $this->make_wx_pay('wechat');
        } else {
            $this->init_wx_pay_for_wxapp();
            $this->make_wx_pay('wxapp');
        }
    }

    private function init_wx_pay_for_gzh($Ischeck = false)
    {
        //这里首先判断 此用户是否绑定了微信公众号
        if ($Ischeck) {
            $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wechat'])->find();
            if (!$third) {
                //从这里自动绑定微信公众号的账户
                $this->error('您未绑定微信号', null, 1008);
            }
        }

        $config = get_addon_config('litestore');

        $third_config = get_addon_config('third');
        $third_options = array_intersect_key($third_config, array_flip(['wechat']));
        $third_options = $third_options['wechat'];

        $options = [
            'debug' => true,
            'log' => [
                'level' => 'debug',
                'file' => '/tmp/easywechat.log',
            ],
            'app_id' => $third_options['app_id'],
            'mch_id' => $config['MCHIDGZH'],
            'key' => $config['APIKEYGZH'],
            'notify_url' => \think\Request::instance()->domain() . '/api/mall.order/callback_for_wxgzh',

        ];
        $this->wxapp = WXPAY_APP::payment($options);
    }

    private function init_wx_pay_for_wxapp()
    {
        $config = get_addon_config('litestore');
        $options = [
            'debug' => true,
            'log' => [
                'level' => 'debug',
                'file' => '/tmp/easywechat.log',
            ],
//            'app_id' => $config['AppID'],
//            'mch_id' => $config['MCHID'],
//            'key' => $config['APIKEY'],
            'app_id' => Config::getConfigByName('mini_appid')['value'],
            'mch_id' => Config::getConfigByName('mch_id')['value'],
            'key' => Config::getConfigByName('mch_key')['value'],
            'notify_url' => \think\Request::instance()->domain() . '/api/mall.order/callback_for_wxapp',

        ];
        $this->wxapp = WXPAY_APP::payment($options);
    }

    private function make_wx_pay($platform)
    {
        $third = Third::where(['user_id' => $this->user_id, 'platform' => $platform])->find();

        $payment = $this->wxapp;

        $attributes = [
            'trade_type' => 'JSAPI',
            'body' => $this->model['order_no'],
            'detail' => 'OrderID:' . $this->model['id'],
            'out_trade_no' => $this->model['order_no'],
            'total_fee' => $this->model['pay_price'] * 100, // 单位：分
//            'total_fee' => 1, // 单位：分
            'openid' => $third['openid'],
        ];
        $result = $payment->order->unify($attributes);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $prepayId = $result['prepay_id'];
            $config = $payment->jssdk->sdkConfig($prepayId);
            return $this->success('预支付成功', $config);
        }
        return $this->error('微信支付调用失败', $result);
    }

    public function callback_for_wxgzh()
    {
        $this->init_wx_pay_for_gzh(false);
        $response = $this->wxapp->handlePaidNotify(function ($message, $fail) {
            $order = $this->model->payDetail($message['out_trade_no']);

            if (empty($order)) { // 如果订单不存在
                return true;
                //return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    $order->updatePayStatus($message['transaction_id']);
                }
            }

            return true; // 返回处理完成
        });

        $response->send();
    }

    public function callback_for_wxapp()
    {
        $this->init_wx_pay_for_wxapp();
        $response = $this->wxapp->handlePaidNotify(function ($message, $fail) {
            $order = $this->model->payDetail($message['out_trade_no']);

            if (empty($order)) { // 如果订单不存在
                return true;
                //return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    $order->updatePayStatus($message['transaction_id']);
                }
            }

            return true; // 返回处理完成
        });

        $response->send();
    }

}
